/*******************************************************
> Copyright (C) 2024 ==iot== All rights reserved.
> File Name: server.c
> Author: wyf
> Created Time: 2024年08月12日 星期一 16时32分39秒
***************************************************/


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h> //目录名获取配合DIR
#include <assert.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h> //文件控制操作
#include <sys/types.h> //获取pid等
#include <sys/wait.h> //等待子进程结束
#include <time.h> //时间获取
#include <sys/ipc.h> //进程通信
#include <sys/msg.h> //消息队列
#include <sys/shm.h> //共享内存
#include <signal.h> //信号处理
#include <pthread.h> //线程
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
//基于udp协议开发一个简易时间服务器。
int main(int argc, const char* argv[])
{

    //创建套接字
    int sock = 0;
    sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock == -1) {
        perror("socket");
    }

    //绑定地址
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = 6742;
    addr.sin_addr.s_addr = inet_addr("192.168.48.128");
    bind(sock, (struct sockaddr*)&addr, sizeof(addr));

    //接收客户端的信息
    struct sockaddr_in client;
    int len = sizeof(client);
    
    //接收数据
    char buf[1024];
    char dest[1024];
    while (1) {
        int ret = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr*)&client, &len);
        if (ret  == -1) {
            perror("recvfrom");
        }
        printf("[%s:%d] %s\n", inet_ntoa(client.sin_addr), client.sin_port, buf);
        printf("Received: [%s]\n", buf);

        if(strcmp(buf, "time") == 0){
            //获取当前时间
            time_t curtime;
            time(&curtime);
            struct tm* localTime;
            localTime = localtime(&curtime);
            sprintf(dest,"%d-%d-%d %d:%d:%d", localTime->tm_year + 1900, localTime->tm_mon + 1, localTime->tm_mday, localTime->tm_hour, localTime->tm_min, localTime->tm_sec);
            ret = sendto(sock, dest, strlen(dest), 0, (struct sockaddr*)&client, sizeof(struct sockaddr));
            printf("exit\n");
            break;
        }
    }

    close(sock);
















    return 0;

}


